import {HttpErrorResponse} from '@angular/common/http';
import {Component, Input, OnInit, OnChanges, ViewChild, SimpleChanges} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {EquipMainDataHttpServices} from '../http/http';


interface UnitTableItem {
  code: string;
  name: string;
  unitDesc: string;
  createUserName: string;
  createTime: string;
  id?: number;
}

@Component(
  {
    selector: `unit-form`,
    template: `
      <form nz-form [formGroup]="unitMgmtForm">
        <nz-form-item>
          <nz-form-label nzRequired [nzSpan]="4">
            单位码
          </nz-form-label>
          <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
            <input nz-input formControlName="code"/>
          </nz-form-control>
        </nz-form-item>
        <nz-form-item>
          <nz-form-label nzRequired [nzSpan]="4">
            单位名称
          </nz-form-label>
          <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
            <input nz-input formControlName="name"/>
          </nz-form-control>
        </nz-form-item>
        <nz-form-item>
          <nz-form-label nzRequired [nzSpan]="4">
            单位描述
          </nz-form-label>
          <nz-form-control nzErrorTip="请输入内容" [nzSpan]="16">
            <input nz-input formControlName="unitDesc"/>
          </nz-form-control>
        </nz-form-item>
      </form>
    `
  }
)

export class UnitFormComponent implements OnChanges {
  constructor(private fb: FormBuilder, private http: EquipMainDataHttpServices) {
  }

  @Input() mode: string;
  @Input() editData: UnitTableItem;
  @Input() unitMgmtForm!: FormGroup;


  onSubmit(successCallback): void {
    if (this.unitMgmtForm.valid) {
      const {code, unitDesc, name} = this.unitMgmtForm.value;
      this.http.createUnit({code, name, unitDesc}).subscribe((res) => {
        if (res.code === 0) {
          successCallback();
        }
      }, (err: HttpErrorResponse) => {
      });
    }
  }

  onUpdate(successCallback): void {
    this.http.updateUnit({...this.unitMgmtForm.value, id: this.editData.id})
      .subscribe((res) => {
        if (res.code === 0) {
          successCallback();
        }
      }, (err: HttpErrorResponse) => {
      });
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (this.mode !== 'create' && this.editData && this.unitMgmtForm) {

      const {code, name, unitDesc} = this.editData;
      this.unitMgmtForm.setValue({code, name, unitDesc});
    }
  }
}


@Component({
  selector: 'app-equip-unit-mgmt',
  styleUrls: ['./components.less'],
  template: `
    <div class="equipMainDataMgmtContainer">
      <div class="equip-main-data-mgmt-bar">
        <div><span>单位码：</span><input nz-input placeholder="输入单位码搜索" [(ngModel)]="keyword"/></div>
        <button nz-button nzType="primary" (click)="loadTable()">查询</button>
        <button nz-button style="background:'green';color:'#ffffff';border-color:'transparent'" (click)="visibleObject.toForm = true">新增
        </button>
      </div>
      <nz-table #unitTable nzSize="middle" [nzShowSizeChanger]="true" [nzShowQuickJumper]="true"
                [nzData]="tableData" [nzLoading]="loading" [nzFrontPagination]="false"
                [nzTotal]="pagination.total" [(nzPageSize)]="pagination.size" [(nzPageIndex)]="pagination.start"
                (nzPageIndexChange)="onPageIndexChange($event)" (nzPageSizeChange)="onPageSizeChange($event)"
      >
        <thead>
        <tr>
          <th>单位码</th>
          <th>单位名称</th>
          <th>单位描述</th>
          <th>创建人</th>
          <th>创建时间</th>
          <th nzAlign="center">操作</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let data of unitTable.data">
          <td>{{ data.code }}</td>
          <td>{{ data.name }}</td>
          <td>{{ data.unitDesc }}</td>
          <td>{{ data.createPeople }}</td>
          <td>{{ data.createTime }}</td>
          <td class='option-td' nzAlign="center">
            <span (click)="onEdit(data)">修改</span>
            <span (click)="visibleObject.toDelete = true; deleteId= data.id">删除</span>
          </td>
        </tr>
        </tbody>
      </nz-table>
    </div>

    <nz-modal [(nzVisible)]="visibleObject.toForm" [nzTitle]="modalTitle" (nzOnCancel)="onCancel()" (nzOnOk)="onSubmit()">
      <ng-template #modalTitle> {{mode === 'create' ? '新增单位' : '修改单位'}}</ng-template>
      <ng-container *nzModalContent>
        <unit-form #myForm [mode]="mode" [editData]="editData" [unitMgmtForm]="unitMgmtForm"></unit-form>
      </ng-container>
    </nz-modal>

    <nz-modal [(nzVisible)]="visibleObject.toDelete" nzTitle="警告" (nzOnCancel)="visibleObject.toDelete=false" (nzOnOk)="onDelete()">
      <ng-container *nzModalContent>
        您确认要删除此项吗？
      </ng-container>
    </nz-modal>
  `
})
export class UnitMgmtComponent implements OnInit {
  constructor(private http: EquipMainDataHttpServices, private fb: FormBuilder) {}

  @ViewChild('myForm') formComponent;
  mode = 'create';
  visibleObject: any = {
    toForm: false,
    toDelete: false
  };
  loading = true;
  keyword = '';
  pagination: any = {
    size: 10,
    start: 1,
    total: undefined,
  };
  tableData!: Array<UnitTableItem>;
  editData!: UnitTableItem;
  deleteId: number;
  unitMgmtForm: any;

  onSubmit(): void {
    if (this.mode === 'create') {
      this.formComponent.onSubmit(() => {
        this.loadTable();
        this.unitMgmtForm.reset();
      });
    } else {
      this.formComponent.onUpdate(() => {
        this.loadTable();
        this.mode = 'create';
        this.unitMgmtForm.reset();
      });
    }

    this.visibleObject.toForm = false;
  }

  loadTable(): void {
    const {start, size} = this.pagination;
    this.http.queryUnit({start: start - 1, size, keyword: this.keyword}).subscribe(
      (res) => {
        if (res.code === 0) {
          this.tableData = res.data.content;
          this.pagination.total = res.data.totalElements;
          this.loading = false;
        }
      }, (err: HttpErrorResponse) => {
        this.loading = false;
        this.tableData = [];
      });
  }

  onCancel(): void {
    this.visibleObject.toForm = false;
    this.mode = 'create';
    this.unitMgmtForm.reset();
  }

  onEdit(data): void {
    this.visibleObject.toForm = true;
    this.mode = 'edit';
    this.editData = data;
  }

  onDelete(): void {
    this.visibleObject.toDelete = false;
    this.http.deleteUnit(this.deleteId).subscribe(
      (res) => {
        if (res.code === 0) {
          this.loadTable();
        }
      }, (err: HttpErrorResponse) => {
      });
  }

  onPageIndexChange(data): void {
    this.pagination.start = data;
    this.loadTable();
  }

  onPageSizeChange(data): void {
    this.pagination.size = data;
    this.loadTable();
  }

  ngOnInit(): void {
    this.loadTable();
    this.unitMgmtForm = this.fb.group({
      code: [null, Validators.required],
      unitDesc: [null, Validators.required],
      name: [null, Validators.required]
    });
  }
}
